package com.shrio.lucene;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by luojie on 2018/4/24.
 */
public class CreateIndex {

    public static void main(String[] args) throws Exception{

            List<Document> docList = new ArrayList<Document>();
            //3、创建Document对象
            Document doc = null;
            File fl = new File("G:\\luceneData");
//        Analyzer analyzer = new StandardAnalyzer();
        IKAnalyzer analyzer = new IKAnalyzer(true);

        // 创建索引库目录。
        Directory directory = FSDirectory.open(new File("G:\\index"));

        // 创建IndexWriterConfig对象
        IndexWriterConfig cfg = new IndexWriterConfig(Version.LATEST, analyzer);

        // 创建IndexWriter对象
        IndexWriter writer = new IndexWriter(directory, cfg);
            //4、为Document添加Field
            for(File file : fl.listFiles()){
                // 创建Document对象，同时要创建Field对象。
                doc = new Document();
                // 根据需求创建不同类型的Field。
                Field id = new TextField("content", readToString(file), Field.Store.YES);
                Field name = new TextField("fileName", file.getName(), Field.Store.YES);
                Field path = new TextField("path", file.getAbsolutePath(), Field.Store.YES);
                doc.add(id);
                doc.add(name);
                doc.add(path);
//                docList.add(doc);
                writer.addDocument(doc);
            }



            // 通过IndexWriter对象添加文档对象（document）
//            for (Document document : docList) {
//                writer.addDocument(document);
//            }

            // 关闭IndexWriter
            writer.close();

    }

    public static String readToString(File file) {
        String encoding = "UTF-8";
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(filecontent, encoding);
        } catch (UnsupportedEncodingException e) {
            System.err.println("The OS does not support " + encoding);
            e.printStackTrace();
            return null;
        }
    }
}
